package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.SQLPageDoing;
import com.rockcent.mall.lib.dto.MallMemberDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by zhangjh on 2017/3/8.
 */
@Repository
public class MallMemberRepositoryImpl implements MallMemberRepositoryCustom {

    private static final Logger log = LoggerFactory.getLogger(MallMemberRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public PageResult<MallMemberDto> findMallMemberPage(MallMemberDto dto, PageResult pageResult) {


        SQLPageDoing doing = (sql, fields, params, typeReferenceMap) -> {
            // a.status,a.name,a.mobile ,b.last_updated ,b.type
            sql.append("select %s from mall_member mm ,mall m where mm.mall_id = m.id");

            Long mallId = dto.getMallId();

            String mallName = dto.getMallName();

            String status = dto.getMemberStatus();

            if (StringUtils.isNotBlank(mallName)) {
                sql.append(" AND m.name like:mallName");
                params.put("mallName", "%" + mallName + "%");
            }

            if (StringUtils.isNotBlank(status)) {
                sql.append(" AND mm.status = :status");
                params.put("status", status);
            }

            if (null != mallId) {
                sql.append(" AND mm.mall_id =:mallId and m.id =:mallId");
                params.put("mallId", mallId);
            }
            sql.append(" order by mm.effect_date desc");
            fields.append(" mm.* ,m.name as mallName, m.company_name companyName");

            log.debug(sql.toString());

        };
        return doing.go(pageResult, MallMemberDto.class, objectMapper, jdbcTemplate, log);
    }
}
